// 路由守卫

import React, { Suspense } from "react";
import { Navigate } from "react-router-dom";
import { profile } from "@depjs/storage";

class RouteGuard extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            isToLoginPage: false,
            from: "",
        };
    }

    static getDerivedStateFromProps(props, state) {
        const l = window.location;
        const href = l.pathname + l.search;

        // console.log('href: ', href);

        const _state = {
            isToLoginPage: false,
            from: "",
        };

        // 登录后阻止用户再回退到登录页
        if (href.includes("/login") && profile.userName && profile.token) {
            window.location.href = "/";
        }

        if (!href.includes("/login") && !(profile.userName && profile.token)) {
            _state.isToLoginPage = true;
            _state.from = href;
        }

        return _state;
    }

    render() {
        const { Com } = this.props;
        const ToCom = this.state.isToLoginPage ? (
            <Navigate
                to="/login"
                replace={true}
                state={{ from: this.state.from }}
            />
        ) : (
            <Suspense fallback={<div>loading...</div>}>
                <Com />
            </Suspense>
        );

        return ToCom;
    }
}

const lazySuspense = (Com) => {
    return <RouteGuard Com={Com} />;
};

export default lazySuspense;
